package cn.lyf.dao;

import cn.lyf.entity.Blog;
import cn.lyf.entity.Body;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

@Repository
public class BlogDaoImpl implements BlogDao {
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public void add(Blog blog) {
     mongoTemplate.save(blog);
    }


    //根据博客类别的id查找对应的所有博客
    @Override
    public List<Blog> findBlogsByTypeId(String typeid) {
        Query query = new Query(Criteria.where("blogtypeid").is(typeid));
        query.with(Sort.by(Sort.Order.desc("tcreate")));
        return  mongoTemplate.find(query,Blog.class);

    }

    //根据id查找对应的博客
    @Override
    public Blog findOneBlog(String blogid) {
        Query query = new Query(Criteria.where("id").is(blogid));
        return mongoTemplate.findOne(query,Blog.class);
    }

    //根据标题模糊查询
    @Override
    public List<Blog> findBlogsByTitle(String title) {
        List<Blog> blogs = new ArrayList<>();
        if(title!=null&&!"".equals(title)){
            Criteria c = new Criteria();
            Pattern pattern = Pattern.compile("^.*"+title+".$",Pattern.CASE_INSENSITIVE);
            c.and("title").regex(pattern);
            Query query = new Query(c);
            blogs= mongoTemplate.find(query,Blog.class);
        }
        return blogs;
    }


}
